package controllers

import (
	"fmt"
	"os"
	"regexp"
	"sort"
	"strings"

	"cvevulner/common"
	"cvevulner/errcode"
	"cvevulner/models"
	"cvevulner/taskhandler"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

// openGauss generates a summary of Sa data and provides an api interface for obtaining data
type GenSaController struct {
	beego.Controller
}

// Manually trigger, generate sa data, and then store the data in the database, a total of api calls
//@router / [get]
func (g *GenSaController) TriggerCveData() {
	var gi taskhandler.GitInfo
	startTime := g.GetString("startTime")
	if startTime == "" {
		g.Ctx.WriteString("Error: startTime cannot be empty")
		return
	}
	gi.StartTime = startTime
	releaseFlag, reErr := g.GetInt("releaseFlag", 1)
	if reErr != nil {
		g.Ctx.WriteString("Error: releaseFlag cannot be empty")
		return
	}
	// Get configuration information
	accessToken := os.Getenv("GITEE_GAUSS_TOKEN")
	if accessToken == "" || len(accessToken) < 1 {
		logs.Error("TriggerCveData, Issue token acquisition failed, "+
			"current time: ", common.GetCurTime())
		g.Ctx.WriteString("Error: Failed to obtain gauss token")
		return
	}
	gi.Token = accessToken
	owner := beego.AppConfig.String("opengauss::gauss_owner")
	gi.Owner = owner
	// Check if the file is being processed
	fileData, fileErr := models.QueryDownloadFile(2)
	if len(fileData) > 0 {
		logs.Info("There are currently files being processed, "+
			"please finish processing before triggering a new sa generation, file: ", fileData)
		g.Ctx.WriteString("processing, There are currently files being processed, " +
			"please finish processing before triggering a new sa generation")
		return
	}
	// Query the file to be downloaded
	fileData, fileErr = models.QueryDownloadFile(1)
	if len(fileData) == 0 {
		logs.Error("QueryDownloadFile, err: ", fileErr)
		g.Ctx.WriteString("Error: There is currently no downloadable file path")
		return
	}
	// Get file storage path
	gaussDir := beego.AppConfig.DefaultString("gaussFileDir", "download/gauss")
	common.CreateAllDir(gaussDir)
	rt := regexp.MustCompile(`^(\d{4})-\d{2}-(\d{2})$`)
	find := rt.Match([]byte(startTime))
	if !find {
		g.Ctx.WriteString(`Error: please enter the correct start time in a format like this "yyyy-MM-dd".`)
		return
	}
	// Define global variables to store cve information
	cveComponent := taskhandler.CveComponent{}
	branchVersion := make([]string, 0)
	for _, fp := range fileData {
		branchVersion = append(branchVersion, fp.RepoVersion)
	}
	// version, descending sort
	sort.Sort(sort.Reverse(sort.StringSlice(branchVersion)))
	// Clear unaffected historical data
	taskhandler.ClearHisDataSa(1)
	// Generate unaffected cve data
	if len(branchVersion) > 0 {
		taskhandler.GaussUnaffectIssue(branchVersion, gi)
	}
	// Clear historical data
	taskhandler.ClearHisDataSa(2)
	saInitValue := int64(0)
	// Get sa initialization variable
	ogs := models.OpenGaussSiteList{}
	qgErr := models.QueryGaussSaMaxValue(&ogs)
	if ogs.GaussId == 0 {
		logs.Info("QueryGaussSaMaxValue, qgErr: ", qgErr)
		saInitValue = beego.AppConfig.DefaultInt64("opengauss::sa_init_value", 1001)
	} else {
		saInitValue = ogs.SaNum + 1
	}
	for _, fExcel := range fileData {
		if releaseFlag == 1 {
			g.Ctx.WriteString(fmt.Sprintf("start：The SA pre-release generation of openGauss has been triggered. "+
				"Please wait patiently for the completion of the data generation. "+
				"It is estimated that it will take a few minutes.", startTime, fExcel.FilePath))
		} else {
			g.Ctx.WriteString(fmt.Sprintf("start：Currently, openGauss SA has been officially released and generated. "+
				"Please wait patiently for the completion of the data generation. "+
				"It is estimated that it will take a few minutes.", startTime, fExcel.FilePath))
		}
		models.UpdateDownloadFile(fExcel.FileId, 2)
		taskhandler.DownloadFileAndParse(fExcel, startTime, gaussDir, &cveComponent)
		models.UpdateDownloadFile(fExcel.FileId, 1)
		// Return the result first, continue processing the data
		if releaseFlag == 1 {
			g.Ctx.WriteString(fmt.Sprintf("Success：The SA pre-release generation of openGauss has been triggered. "+
				"Please wait patiently for the completion of the data generation. "+
				"It is estimated that it will take a few minutes.", startTime, fExcel.FilePath))
		} else {
			g.Ctx.WriteString(fmt.Sprintf("Success：Currently, openGauss SA has been officially released and generated. "+
				"Please wait patiently for the completion of the data generation. "+
				"It is estimated that it will take a few minutes.", startTime, fExcel.FilePath))
		}
	}
	// Merging of multi-branch data
	MergMultiBranchData(branchVersion, cveComponent, &saInitValue)
	// Upgrade pre-release data to official data
	if releaseFlag == 2 {
		models.UpdateGaussPreTRelease()
	}
}

func MergMultiBranchData(branchVersion []string, cveComponent taskhandler.CveComponent, saInitValue *int64) {
	bVersionSlice := make([]string, 0)
	if cveComponent.PackMap != nil && len(cveComponent.PackMap) > 0 {
		for k, v := range cveComponent.PackMap {
			isEque := true
			iFlag := 0
			for i, bv := range branchVersion {
				_, ok1 := v.BranchMap[bv]
				if ok1 {
					iFlag = i
					break
				}
			}
			bv1 := v.BranchMap[branchVersion[iFlag]]
			if (iFlag + 1) <= (len(branchVersion) - 1) {
				for _, branchInfo := range branchVersion[iFlag+1:] {
					bv2, ok2 := v.BranchMap[branchInfo]
					if ok2 {
						if !common.CompareSlice(bv1, bv2) {
							isEque = false
							break
						}
					}

				}
			}
			for _, bv := range branchVersion {
				_, ok1 := v.BranchMap[bv]
				if ok1 {
					addBs := false
					for _, vj := range bVersionSlice {
						if vj == bv {
							addBs = true
							break
						}
					}
					if !addBs {
						bVersionSlice = append(bVersionSlice, bv)
					}
				}
			}
			taskhandler.PreGeneratedSaData(k, bVersionSlice, isEque, saInitValue)
		}
	}
}

type GaussSaController struct {
	beego.Controller
}

func (c *GaussSaController) RetSaData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

type GaussSaData struct {
	SaId               int64  `json:"saId"`
	GaussSaNum         string `json:"gaussSaNum"`
	Summary            string `json:"summary"`
	CveLevel           string `json:"cveLevel"`
	CveLevelValue      int    `json:"cveLevelValue"`
	AffectProduct      string `json:"affectProduct"`
	InfluenceComponent string `json:"influenceComponent"`
	ReleaseDate        string `json:"releaseDate"`
}

// @Get the information of the SA that has been generated
// @Description get gauss sa
// @router / [get]
func (u *GaussSaController) Get() {
	req := u.Ctx.Request
	addr := req.RemoteAddr
	logs.Info("Method: ", req.Method, "Client request ip address: ", addr,
		", Header: ", req.Header, ", body: ", req.Body)
	resp := make(map[string]interface{})
	var gs []GaussSaData
	resp["code"] = errcode.RecodeNodata
	resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
	resp["body"] = []GaussSaData{}
	resp["totalCount"] = 0
	resp["totalPage"] = 0
	//defer u.RetSaData(resp)
	cveLevel, cErr := u.GetInt("cveLevel", 0)
	if cErr != nil {
		cveLevel = 0
	}
	years, yErr := u.GetInt("years", 0)
	if yErr != nil {
		years = 0
	}
	releaseFlag, rErr := u.GetInt("releaseFlag", 1)
	if rErr != nil {
		releaseFlag = 1
	}
	searchName := u.GetString("searchName", "")
	count := models.QueryGaussSaCount(cveLevel, years, releaseFlag, searchName)
	if count > 0 {
		resp["totalCount"] = count
		resp["code"] = errcode.RecodeOk
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
		pageNum, err := u.GetInt("pageNum", 1)
		if err != nil {
			logs.Error("err: ", err, ", pageNum: ", pageNum)
			resp["errno"] = errcode.RecodeParamErr
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
			u.RetSaData(resp)
			return
		}
		pageSize, err := u.GetInt("pageSize", 100)
		if err != nil {
			logs.Error("err: ", err, ", pageSize: ", pageSize)
			resp["errno"] = errcode.RecodeParamErr
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
			u.RetSaData(resp)
			return
		}
		if int(count) % pageSize == 0 {
			resp["totalPage"] = int(count) / pageSize
		} else {
			resp["totalPage"] = int(count) / pageSize + 1
		}
		saData, saErr := models.QueryOpenGaussSiteList(pageNum, pageSize, cveLevel, years, releaseFlag, searchName)
		if len(saData) > 0 {
			for _, sa := range saData {
				var irda GaussSaData
				irda.SaId = sa.GaussId
				irda.GaussSaNum = sa.GaussSaNum
				irda.Summary = sa.Summary
				irda.CveLevel = sa.CveLevel
				irda.CveLevelValue = sa.CveLevelValue
				irda.InfluenceComponent = sa.InfluenceComponent
				if len(sa.CreateTime) > 10 {
					irda.ReleaseDate = sa.CreateTime[:10]
				} else {
					irda.ReleaseDate = sa.CreateTime
				}
				irda.AffectProduct = sa.AffectProduct
				irda.AffectProduct = strings.ReplaceAll(irda.AffectProduct, "/", " / ")
				gs = append(gs, irda)
			}
			resp["body"] = gs
			resp["code"] = errcode.RecodeOk
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
			u.RetSaData(resp)
		} else {
			logs.Error("QueryOpenGaussSiteList, saErr: ", saErr)
			resp["code"] = errcode.RecodeNodata
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
			u.RetSaData(resp)
			return
		}
	} else {
		resp["code"] = errcode.RecodeNodata
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
		u.RetSaData(resp)
		return
	}
}

type GaussTag struct {
	PackageName      string   `json:"packageName"`
	AffectedPlatform []string `json:"affectedPlatform"`
}

type GaussPackage struct {
	GroupName string     `json:"groupName"`
	GaussTag  []GaussTag `json:"tagBody"`
}

type GaussVersions struct {
	Versions     string         `json:"versions"`
	GaussPackage []GaussPackage `json:"packageBody"`
}

type GaussSaDetailData struct {
	GaussSaNum         string          `json:"gaussSaNum"`
	Summary            string          `json:"summary"`
	CveLevel           string          `json:"cveLevel"`
	CveLevelValue      int             `json:"cveLevelValue"`
	AffectProduct      string          `json:"affectProduct"`
	InfluenceComponent string          `json:"influenceComponent"`
	ReleaseDate        string          `json:"releaseDate"`
	Introduction       string          `json:"introduction"`
	Theme              string          `json:"theme"`
	Description        string          `json:"description"`
	CveNumbers         string          `json:"cveNumbers"`
	ReferenceLink      string          `json:"referenceLink"`
	GaussVersions      []GaussVersions `json:"versionsBody"`
}

type GaussSaDetailController struct {
	beego.Controller
}

func (c *GaussSaDetailController) RetSaDetailData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

// @Title Get GaussSaDetailController
// @Description get sa detail
// @router / [get]
func (u *GaussSaDetailController) Get() {
	req := u.Ctx.Request
	addr := req.RemoteAddr
	logs.Info("Method: ", req.Method, "Client request ip address: ", addr,
		", Header: ", req.Header, ", body: ", req.Body)
	resp := make(map[string]interface{})
	var ird GaussSaDetailData
	resp["errno"] = errcode.RecodeUnknowErr
	resp["errmsg"] = errcode.RecodeText(errcode.RecodeUnknowErr)
	resp["body"] = GaussSaDetailData{}
	//defer u.RetSaDetailData(resp)
	gaussSaNum := u.GetString("gaussSaNum", "")
	if gaussSaNum == "" {
		resp["errno"] = errcode.RecodeParamErr
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
		u.RetSaDetailData(resp)
		return
	}
	osl := models.OpenGaussSiteList{GaussSaNum: gaussSaNum}
	oslErr := models.QueryOpenGaussSaByNum(&osl, "GaussSaNum")
	if osl.GaussId > 0 {
		CreateSaDetailData(&ird, osl)
		resp["body"] = ird
		resp["errno"] = errcode.RecodeOk
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
		u.RetSaDetailData(resp)
	} else {
		logs.Error("QueryOpenGaussSaByNum, oslErr: ", oslErr)
		resp["errno"] = errcode.RecodeNodata
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
		u.RetSaDetailData(resp)
		return
	}
}

func CreateSaDetailData(ird *GaussSaDetailData, osl models.OpenGaussSiteList) {
	nvdRelink := beego.AppConfig.String("opengauss::nvd_relink")
	ird.GaussSaNum = osl.GaussSaNum
	ird.AffectProduct = osl.AffectProduct
	ird.Summary = osl.Summary
	ird.Introduction = osl.Introduction
	ird.CveLevel = osl.CveLevel
	ird.CveLevelValue = osl.CveLevelValue
	ird.InfluenceComponent = osl.InfluenceComponent
	if len(osl.CreateTime) > 10 {
		ird.ReleaseDate = osl.CreateTime[:10]
	} else {
		ird.ReleaseDate = osl.CreateTime
	}
	ird.Theme = osl.Theme
	ird.Description = osl.Description
	if strings.Index(ird.Description, "\n\n") >= 0 {
		ird.Description = strings.ReplaceAll(ird.Description, "\n\n", "<br/>")
	}else if strings.Index(ird.Description, "\n") >= 0 {
		ird.Description = strings.ReplaceAll(ird.Description, "\n", "<br/>")
	}
	ird.CveNumbers = osl.CveNums
	cveLinkSlice := make([]string, 0)
	if len(osl.CveNums) > 1 {
		cveNumSlice := strings.Split(osl.CveNums, ";")
		if len(cveNumSlice) > 0 {
			for _, cve := range cveNumSlice {
				cveLinkSlice = append(cveLinkSlice, nvdRelink+cve)
			}
		}
	}
	if len(cveLinkSlice) > 0 {
		ird.ReferenceLink = strings.Join(cveLinkSlice, ";")
	}
	gv := make([]GaussVersions, 0)
	// Query the associated version information
	if len(osl.AffectProduct) > 0 {
		affectSlice := strings.Split(osl.AffectProduct, "/")
		if len(affectSlice) > 0 {
			for _, affect := range affectSlice {
				var lgv GaussVersions
				lgv.Versions = affect
				ogp, pErr := models.QueryGaussPackageByGid(osl.GaussId, affect)
				if len(ogp) > 0 {
					groupMap := make(map[int64]map[string][]int64)
					for _, gp := range ogp {
						groupV, ok := groupMap[gp.GroupId]
						if !ok {
							platMap := make(map[string][]int64)
							paltSlice := make([]int64, 0)
							paltSlice = append(paltSlice, gp.PlatId)
							platMap[gp.RpmName] = paltSlice
							groupMap[gp.GroupId] = platMap
						} else {
							platV, ok := groupV[gp.RpmName]
							if !ok {
								paltSlice := make([]int64, 0)
								paltSlice = append(paltSlice, gp.PlatId)
								groupV[gp.RpmName] = paltSlice
							} else {
								vIsExit := false
								for _, pv := range platV {
									if pv == gp.PlatId {
										vIsExit = true
										break
									}
								}
								if !vIsExit {
									platV = append(platV, gp.PlatId)
									groupV[gp.RpmName] = platV
								}
							}
						}
					}
					if len(groupMap) > 0 {
						gp := make([]GaussPackage, 0)
						for kg, vg := range groupMap {
							ogg := models.OpenGaussGroup{GroupId: kg}
							gErr := models.QueryOpenGaussGroup(&ogg, "GroupId")
							if gErr == nil {
								var ge GaussPackage
								ge.GroupName = ogg.GroupName
								tag := make([]GaussTag, 0)
								for pgk, pgv := range vg {
									var tagv GaussTag
									tagv.PackageName = pgk
									ogl, opErr := models.QueryGaussPlatByPids(pgv)
									if len(ogl) > 0 {
										plSlice := make([]string, 0)
										for _, pl := range ogl {
											plSlice = append(plSlice, pl.PlatName)
										}
										tagv.AffectedPlatform = plSlice
									} else {
										logs.Error("QueryGaussPlatByPids, opErr: ", opErr)
									}
									tag = append(tag, tagv)
								}
								ge.GaussTag = tag
								gp = append(gp, ge)
							}
						}
						lgv.GaussPackage = gp
					}
				} else {
					logs.Error("QueryGaussPackageByGid, pErr: ", pErr)
				}
				gv = append(gv, lgv)
			}
		}
	}
	ird.GaussVersions = gv
}

type GaussCveController struct {
	beego.Controller
}

func (c *GaussCveController) RetGaussCveData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

type GaussCveData struct {
	CveId       int64   `json:"cveId"`
	CveNum      string  `json:"cveNum"`
	Description string  `json:"description"`
	NvdScore    float64 `json:"NVDScore"`
	UpdateTime  string  `json:"updateTime"`
	ReleaseDate string  `json:"releaseDate"`
}

// @Get the cve information of gauss
// @Description get gauss cve
// @router / [get]
func (u *GaussCveController) Get() {
	req := u.Ctx.Request
	addr := req.RemoteAddr
	logs.Info("Method: ", req.Method, "Client request ip address: ", addr,
		", Header: ", req.Header, ", body: ", req.Body)
	resp := make(map[string]interface{})
	var gs []GaussCveData
	resp["code"] = errcode.RecodeNodata
	resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
	resp["body"] = []GaussCveData{}
	resp["totalCount"] = 0
	resp["totalPage"] = 0
	//defer u.RetGaussCveData(resp)
	releaseFlag, rErr := u.GetInt("releaseFlag", 1)
	if rErr != nil {
		releaseFlag = 1
	}
	isAffectFlag, rErr := u.GetInt("isAffectFlag", 1)
	if rErr != nil {
		isAffectFlag = 1
	}
	searchName := u.GetString("searchName", "")
	count := models.QueryGaussCveCount(releaseFlag, isAffectFlag, searchName)
	if count > 0 {
		resp["totalCount"] = count
		resp["code"] = errcode.RecodeOk
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
		pageNum, err := u.GetInt("pageNum", 1)
		if err != nil {
			logs.Error("err: ", err, ", pageNum: ", pageNum)
			resp["errno"] = errcode.RecodeParamErr
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
			u.RetGaussCveData(resp)
			return
		}
		pageSize, err := u.GetInt("pageSize", 100)
		if err != nil {
			logs.Error("err: ", err, ", pageSize: ", pageSize)
			resp["errno"] = errcode.RecodeParamErr
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
			u.RetGaussCveData(resp)
			return
		}
		if int(count) % pageSize == 0 {
			resp["totalPage"] = int(count) / pageSize
		} else {
			resp["totalPage"] = int(count) / pageSize + 1
		}
		saData, saErr := models.QueryOpenGaussCveList(pageNum, pageSize, releaseFlag, isAffectFlag, searchName)
		if len(saData) > 0 {
			for _, sa := range saData {
				var irda GaussCveData
				irda.CveId = sa.Id
				irda.CveNum = sa.CveNum
				irda.Description = sa.Description
				irda.NvdScore = sa.NVDScore
				irda.UpdateTime = sa.UpdateTime
				if len(sa.CreateTime) > 10 {
					irda.ReleaseDate = sa.CreateTime[:10]
				} else {
					irda.ReleaseDate = sa.CreateTime
				}
				gs = append(gs, irda)
			}
			resp["body"] = gs
			resp["code"] = errcode.RecodeOk
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
			u.RetGaussCveData(resp)
		} else {
			logs.Error("QueryOpenGaussCveList, saErr: ", saErr)
			resp["code"] = errcode.RecodeNodata
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
			u.RetGaussCveData(resp)
			return
		}
	} else {
		resp["code"] = errcode.RecodeNodata
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
		u.RetGaussCveData(resp)
		return
	}
}

type GaussCveAffectProduct struct {
	AffectProduct string `json:"affectProduct"`
	PackName      string `json:"packName"`
	FixLabel      string `json:"fixLabel"`
}

type GaussCveSa struct {
	GaussSaNum  string `json:"gaussSaNum"`
	SaId        int64  `json:"saId"`
	Summary     string `json:"summary"`
	ReleaseDate string `json:"releaseDate"`
}

type GaussCveCvssV3 struct {
	NvdScore           float64 `json:"NVDScore"`
	OpenGaussScore     float64 `json:"openGaussScore"`
	NAttackVector      string  `json:"nAttackVector"`
	OAttackVector      string  `json:"oAttackVector"`
	NAttackComplexity  string  `json:"nAttackComplexity"`
	OAttackComplexity  string  `json:"oAttackComplexity"`
	NPrivilegeRequired string  `json:"nPrivilegeRequired"`
	OPrivilegeRequired string  `json:"oPrivilegeRequired"`
	NUserInteraction   string  `json:"nUserInteraction"`
	OUserInteraction   string  `json:"oUserInteraction"`
	NScope             string  `json:"nScope"`
	OScope             string  `json:"oScope"`
	NConfidentiality   string  `json:"nConfidentiality"`
	OConfidentiality   string  `json:"oConfidentiality"`
	NIntegrity         string  `json:"nIntegrity"`
	OIntegrity         string  `json:"oIntegrity"`
	NAvailability      string  `json:"nAvailability"`
	OAvailability      string  `json:"oAvailability"`
	ScoreType          string  `json:"scoreType"`
}

type GaussCveDetailData struct {
	CveId       int64                   `json:"cveId"`
	CveNum      string                  `json:"cveNum"`
	Description string                  `json:"description"`
	NvdScore    float64                 `json:"NVDScore"`
	UpdateTime  string                  `json:"updateTime"`
	ReleaseDate string                  `json:"releaseDate"`
	CVSSV3      GaussCveCvssV3          `json:"CVSSV3"`
	SaBody      GaussCveSa              `json:"saBody"`
	AffectBody  []GaussCveAffectProduct `json:"affectBody"`
}

type GaussCveDetailController struct {
	beego.Controller
}

func (c *GaussCveDetailController) RetCveDetailData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

// @Title Get GaussSaDetailController
// @Description get sa detail
// @router / [get]
func (u *GaussCveDetailController) Get() {
	req := u.Ctx.Request
	addr := req.RemoteAddr
	logs.Info("Method: ", req.Method, "Client request ip address: ", addr,
		", Header: ", req.Header, ", body: ", req.Body)
	resp := make(map[string]interface{})
	var ird GaussCveDetailData
	resp["errno"] = errcode.RecodeUnknowErr
	resp["errmsg"] = errcode.RecodeText(errcode.RecodeUnknowErr)
	resp["body"] = GaussCveDetailData{}
	//defer u.RetCveDetailData(resp)
	cveNum := u.GetString("cveNum", "")
	if cveNum == "" {
		resp["errno"] = errcode.RecodeParamErr
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeParamErr)
		u.RetCveDetailData(resp)
		return
	}
	osl := models.OpenGaussCveList{CveNum: cveNum}
	oslErr := models.QueryOpenGaussCveByNum(&osl, "CveNum")
	if osl.Id > 0 {
		CreateCveDetailData(&ird, osl)
		resp["body"] = ird
		resp["errno"] = errcode.RecodeOk
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
		u.RetCveDetailData(resp)
	} else {
		logs.Error("QueryOpenGaussCveByNum, oslErr: ", oslErr)
		resp["errno"] = errcode.RecodeNodata
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeNodata)
		u.RetCveDetailData(resp)
		return
	}
}

func CreateCveDetailData(gdd *GaussCveDetailData, ocl models.OpenGaussCveList) {
	gdd.CveId = ocl.Id
	gdd.CveNum = ocl.CveNum
	gdd.Description = ocl.Description
	if strings.Index(gdd.Description, "\n\n") >= 0 {
		gdd.Description = strings.ReplaceAll(gdd.Description, "\n\n", "<br/>")
	}else if strings.Index(gdd.Description, "\n") >= 0 {
		gdd.Description = strings.ReplaceAll(gdd.Description, "\n", "<br/>")
	}
	gdd.NvdScore = ocl.NVDScore
	gdd.UpdateTime = ocl.UpdateTime
	if len(ocl.CreateTime) > 10 {
		gdd.ReleaseDate = ocl.CreateTime[:10]
	} else {
		gdd.ReleaseDate = ocl.CreateTime
	}
	var gcv GaussCveCvssV3
	gcv.NvdScore = ocl.NVDScore
	gcv.OpenGaussScore = ocl.OpenEulerScore
	gcv.NAttackVector = ocl.NattackVector
	gcv.OAttackVector = ocl.OattackVector
	gcv.NAttackComplexity = ocl.NattackComplexity
	gcv.OAttackComplexity = ocl.OattackComplexity
	gcv.NPrivilegeRequired = ocl.NprivilegeRequired
	gcv.OPrivilegeRequired = ocl.OprivilegeRequired
	gcv.NUserInteraction = ocl.NuserInteraction
	gcv.OUserInteraction = ocl.OuserInteraction
	gcv.NScope = ocl.Nscope
	gcv.OScope = ocl.Oscope
	gcv.NConfidentiality = ocl.Nconfidentiality
	gcv.OConfidentiality = ocl.Oconfidentiality
	gcv.NIntegrity = ocl.Nintegrity
	gcv.OIntegrity = ocl.Ointegrity
	gcv.NAvailability = ocl.Navailability
	gcv.OAvailability = ocl.Oavailability
	gcv.ScoreType = ocl.ScoreType
	gdd.CVSSV3 = gcv
	if ocl.GaussId > 0 {
		ost := models.OpenGaussSiteList{GaussId: ocl.GaussId}
		ostErr := models.QueryOpenGaussSaByNum(&ost, "GaussId")
		if ostErr == nil {
			var gs GaussCveSa
			gs.SaId = ost.GaussId
			gs.Summary = ost.Summary
			gs.GaussSaNum = ost.GaussSaNum
			if len(ost.CreateTime) > 10 {
				gs.ReleaseDate = ost.CreateTime[:10]
			} else {
				gs.ReleaseDate = ost.CreateTime
			}
			gdd.SaBody = gs
		}
	} else {
		gdd.SaBody = GaussCveSa{}
	}
	ogv, ogvErr := models.QueryGaussVersionByCid(gdd.CveId)
	if len(ogv) > 0 {
		gcp := make([]GaussCveAffectProduct, 0)
		for _, gv := range ogv {
			var gp GaussCveAffectProduct
			gp.AffectProduct = gv.RepoVersion
			gp.PackName = ocl.PackName
			gp.FixLabel = gv.AffectStatusName
			gcp = append(gcp, gp)
		}
		gdd.AffectBody = gcp
	} else {
		logs.Error("QueryGaussVersionByCid, ogvErr: ", ogvErr)
	}
}
